package com.xuanwei.admin.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuanwei.core.response.ResultVO;
import com.xuanwei.core.entity.bo.UserDetail;
import com.xuanwei.core.exception.XwException;
import com.xuanwei.core.service.IXwLoginLogService;
import com.xuanwei.core.service.IXwManagementService;
import com.xuanwei.core.util.ParamUtil;
import com.xuanwei.dao.entity.XwLoginLog;
import com.xuanwei.dao.entity.XwManagement;
import com.xuanwei.xwcommon.consts.CacheName;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author mjy
 * @since 2019-04-14
 */
@RestController
@RequestMapping("api/admin")
public class ManagementController extends BasicController {

    @Autowired
    private IXwManagementService managementService;

    @Autowired
    private IXwLoginLogService loginLogService;

    @RequestMapping(value = "login.do", method = RequestMethod.POST)
    public ResultVO login(HttpServletRequest request, String username, String password, String code) {
        if (!ParamUtil.checkIsString(username)) {
            return ResultVO.failResult("请输入用户名");
        }
        if (!ParamUtil.checkIsString(password)) {
            return ResultVO.failResult("请输入密码");
        }
        if (!ParamUtil.checkIsString(code)) {
            return ResultVO.failResult("请输入验证码");
        }
        Object attribute = request.getSession().getAttribute(CacheName.CODE);
        if (attribute == null) {
            return ResultVO.failResult("请先获取验证码");
        }
        if (!attribute.toString().equals(code)) {
            return ResultVO.failResult("验证码错误");
        }

        String token = managementService.login(username, password);
        request.getSession().removeAttribute(CacheName.CODE);
        XwLoginLog loginLog = new XwLoginLog();
        loginLog.setLoginIp(getIpAddress(request));
        loginLog.setLoginTime(LocalDateTime.now());
        loginLog.setManagementId(getId());
        loginLog.setManagementNickname(getUser().getNickname());
        loginLog.setLoginAddress("未知");
        loginLogService.add(loginLog);
        return ResultVO.successResult("登陆成功", token);

    }


    @RequestMapping(value = "logout.do", method = RequestMethod.GET)
    public ResultVO logout() {
        try {
            managementService.logout();
            return ResultVO.successResult("退出成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVO.successResult("退出失败");
        }

    }

    @RequestMapping(value = "permissions.do", method = RequestMethod.GET)
    public ResultVO permissions() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        List<String> auths = authorities.stream().map(s -> s.getAuthority()).collect(Collectors.toList());
        UserDetail principal = (UserDetail) authentication.getPrincipal();
        Map<String,Object> map=new HashMap<>();
        map.put("nickname",principal.getManagement().getNickname());
        map.put("avatar",principal.getManagement().getAvatar());
        map.put("authorities",auths);
        return ResultVO.successResult(map);
    }


    @RequestMapping(value = "addOrUpdate.do", method = RequestMethod.POST)
    public ResultVO addOrUpdate(XwManagement management) {

        if (!ParamUtil.checkIsString(management.getNickname())) {
            return ResultVO.failResult("昵称格式错误");
        }

        if (!ParamUtil.checkIsUsername(management.getUsername())) {
            return ResultVO.failResult("用户格式错误");
        }

        if (!ParamUtil.checkIsPassword(management.getPassword())) {
            return ResultVO.failResult("密码格式错误");
        }

        if (!ParamUtil.checkIsPositiveInteger(management.getRoleId())) {
            return ResultVO.failResult("角色格式错误");
        }

        if (!ParamUtil.checkIsString(management.getRoleName())) {
            return ResultVO.failResult("角色格式错误");
        }

        try {
            managementService.addOrUpdate(management);
            return ResultVO.successResult("操作成功");
        } catch (XwException e) {
            return ResultVO.failResult(e.getMessage());
        }


    }

    @RequestMapping(value = "list.do", method = RequestMethod.GET)
    public ResultVO list(Integer size, Integer index) {
        if (!ParamUtil.checkIsPositiveInteger(index)) {
            index = 1;
        }
        if (!ParamUtil.checkIsPositiveInteger(size)) {
            size = 20;
        }
        Page<XwManagement> page = new Page<>(index, size);
        managementService.list(page);
        return ResultVO.successResult(page);
    }

    @RequestMapping(value = "delete.do", method = RequestMethod.GET)
    public ResultVO delete(Integer id) {
        if (!ParamUtil.checkIsPositiveInteger(id)) {
            return ResultVO.failResult("ID参数格式错误");
        }
        managementService.delete(id);
        return ResultVO.successResult("删除成功");
    }


}
